package xyx.chenweb.myapp.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import xyx.chenweb.myapp.entity.UserInfo;
import xyx.chenweb.myapp.mapper.mapping.UserInfoMapping;
import xyx.chenweb.myapp.utils.MyResponseData;
import xyx.chenweb.myapp.utils.MyTools;

@Service
public class UserOptionService {

    @Autowired
    private UserInfoMapping userInfoMapping;

    @Autowired
    private ApiService apiService;

    @Autowired
    private EhcacheService ehcacheService;

    public MyResponseData changePwd(String oldPwd, String newPwd){
        MyResponseData myResponseData = new MyResponseData();
        Subject subject = SecurityUtils.getSubject();
        String userId = subject.getPrincipal().toString();
        UserInfo userInfo = userInfoMapping.selectById(userId);
        if(MyTools.isEmpty(userInfo)){
            myResponseData.setCode(500);
            myResponseData.setMessage("修改密码失败！");
            return myResponseData;
        }

        String userSalt = userInfo.getUserSalt();
        String userPwd = userInfo.getUserPwd();

        //加密获取对照密码
        String checkPwd = new Md5Hash(oldPwd, userSalt, 1024).toHex();

        //密码对比
        if(!userPwd.equals(checkPwd)){
            myResponseData.setCode(500);
            myResponseData.setMessage("原密码错误！");
            return myResponseData;
        }

        String newPassword = new Md5Hash(newPwd, userSalt,1024).toHex();
        userInfo.setUserPwd(newPassword);
        userInfoMapping.updateById(userInfo);

        //强制用户退出登录
        apiService.logout();

        myResponseData.setCode(200);
        myResponseData.setMessage("用户密码修改成功！");

        return myResponseData;
    }

    public MyResponseData userInfor(){
        MyResponseData myResponseData = new MyResponseData();
        Subject subject = SecurityUtils.getSubject();
        String id = null;
        if(!MyTools.isEmpty(subject.getPrincipal())){
            id = subject.getPrincipal().toString();
        }

        //退出登录也无法获取用户
        if(MyTools.isEmpty(id)){
            myResponseData.setMessage("用户未登录");
            myResponseData.setCode(500);
            return myResponseData;
        }

        UserInfo userInfo = ehcacheService.getUser(id);
        if (MyTools.isEmpty(userInfo)){

            //如果在缓存中清除用户信息，可以强制让其退出登录
            myResponseData.setMessage("用户信息过期");
            myResponseData.setCode(500);
            subject.logout();
        }

        myResponseData.setCode(200);
        myResponseData.setData(userInfo);
        return myResponseData;
    }
}
